package com.frxuexi.park2209.user

import androidx.lifecycle.MutableLiveData
import com.frxuexi.base.db.UserDao
import com.frxuexi.base.entity.UserBean
import com.frxuexi.base.mvvm.BaseViewModel
import com.frxuexi.base.net.ApiService
import com.google.gson.Gson
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import javax.inject.Inject

@HiltViewModel
class LoginViewModel @Inject constructor(val apiService: ApiService,val userDao: UserDao):BaseViewModel() {

//    val loginSuccess by lazy { MutableLiveData<String>() }
    val loginSuccess by lazy { MutableLiveData<UserBean>() }

    var registerSuc =MutableStateFlow<Long>(-1)
    fun login(map: Map<String,String>){
        httpRequest({apiService.login(mapToBody(map))},
//            loginSuccess::postValue
            {
                val userBean = Gson().fromJson(it, UserBean::class.java)
                val token = userBean.token
                roomRequest({userDao.login(map["uName"].toString(),map["uPwd"]!!.toInt())},
//                    loginSuccess::postValue
                    {
                        it.token=token
                        roomRequest({userDao.updateToken(it)},{loginSuccess.value=userBean})
                    }
                )
            }
        )

    }

    fun register(userBean: UserBean){
        roomRequest({userDao.register(userBean)},{
            registerSuc.value=it
        })
    }
}